package com.yunxin.admin.system.api.core.order;
import java.nio.charset.StandardCharsets;
import cn.hutool.core.collection.CollUtil;
import com.yunxin.admin.system.application.UserQueryService;
import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
import com.yunxin.admin.system.infra.common.enums.AdminResultCode;
import com.yunxin.admin.system.infra.framework.resubmit.Resubmit;
import com.yunxin.admin.system.infra.framework.security.util.SecurityUtils;
import com.yunxin.admin.system.infra.framework.syslog.AutoLog;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.result.PageResult;
import com.yunxin.common.result.Result;
import com.yunxin.core.application.command.order.*;
import com.yunxin.core.application.dto.order.ChannelPromotionTwoUvStatisticsDto;
import com.yunxin.core.application.dto.order.OrderUserApplyAllocationMerchantPageDTO;
import com.yunxin.core.application.dto.order.OrderUserApplyAllocationPageDTO;
import com.yunxin.core.application.dto.product.ProductDetailDTO;
import com.yunxin.core.application.dto.product.ProductListDTO;
import com.yunxin.core.application.service.OrderApplicationAdminService;
import com.yunxin.core.application.service.OrderQueryAdminService;
import com.yunxin.core.application.service.ProductQueryAdminService;
import com.yunxin.core.application.service.TeamService;
import com.yunxin.core.domain.model.team.Team;
import com.yunxin.core.utils.infra.utils.DateFormatUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * @author zero°
 * @since 2023-05-29
 */
@Tag(name = "31.订单管理")
@Slf4j
@RestController
@RequestMapping("/core/v1/order/user/apply/allocation")
@RequiredArgsConstructor
public class OrderUserApplyAllocationController {

    private final OrderQueryAdminService orderQueryAdminService;

    private final OrderApplicationAdminService orderApplicationAdminService;

    private final UserQueryService userQueryService;

    private final ProductQueryAdminService productQueryAdminService;

    private final TeamService teamService;
//
//
//    @Operation(summary = "解除分配订单账户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping("/deallocateOrderAccount")
//    @PreAuthorize("@ss.hasPerm('core:order:allcation:deallocate')")
//    @Resubmit
//    @AutoLog(value = "解除分配订单账户")
//    public Result<Boolean> deallocateOrderAccount(@Validated @RequestBody OperateAllocationOrderAccountCommand command) {
//        if (!SecurityUtils.X.isMerchantAdmin() && !SecurityUtils.X.isTeamAdmin()) {
//            throw new BusinessException(AdminResultCode.ADMIN_MERCHANT_ROLE_ERROR);
//        }
//        command.setOperator(SecurityUtils.X.getUser().getUsername());
//        command.setAccountId(null);
//        return Result.success(orderApplicationAdminService.operateAllocationOrderAccount(command));
//    }
//
//    @Operation(summary = "重新分配订单账户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping("/redistributionOrderAccount")
//    @PreAuthorize("@ss.hasPerm('core:order:allcation:redistribution')")
//    @Resubmit
//    @AutoLog(value = "重新分配订单账户")
//    public Result<Boolean> redistributionOrderAccount(@Validated @RequestBody OperateAllocationOrderAccountCommand command) {
//        if (!SecurityUtils.X.isMerchantAdmin() && !SecurityUtils.X.isTeamAdmin()) {
//            throw new BusinessException(AdminResultCode.ADMIN_MERCHANT_ROLE_ERROR);
//        }
//        if (Objects.isNull(command.getAccountId())) {
//            throw new BusinessException(AdminResultCode.PARAM_ERROR);
//        }
//        command.setOperator(SecurityUtils.X.getUser().getUsername());
//
//        if(orderApplicationAdminService.operateAllocationOrderAccount(command)) {
//            return Result.success();
//        }  else {
//            return Result.failed("处理失败！");
//        }
//    }
//
//    @Operation(summary = "操作分配订单状态", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping("/operateAllocationOrderStatus")
//    @PreAuthorize("@ss.hasPerm('core:order:allcation:status:edit')")
//    @Resubmit
//    @AutoLog(value = "操作分配订单状态")
//    public Result<Boolean> operateAllocationOrderStatus(@Validated @RequestBody OperateAllocationOrderStatusCommand command) {
//        command.setOperator(SecurityUtils.X.getUser().getUsername());
//        return Result.success(orderApplicationAdminService.operateAllocationOrderStatus(command));
//    }
//
//    @Operation(summary = "分页查询用户申请分配订单列表-商户端", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping("/orderUserApplyAllocationPageQueryByDataRole")
//    public PageResult<OrderUserApplyAllocationMerchantPageDTO> orderUserApplyAllocationPageQueryByDataRole(@Validated @RequestBody OrderUserApplyAllocationMerchantPageCommand command) {
//        final Long userId = SecurityUtils.X.getUser().getUserId();
//        List<Long> merchantIds = userQueryService.getUserMerchantIds(userId);
//        if (CollUtil.isEmpty(merchantIds)) {
//            return PageResult.success(Collections.emptyList(), 0);
//        }
//        command.setMerchantId(merchantIds.get(0));
//        //商户用户角色只能查询自己的数据
//        if (SecurityUtils.X.isMerchantUser()) {
//            command.setSysUserId(userId);
//        }
//        //团队管理员只能自己团队下的未接通列表
//        if (SecurityUtils.X.isTeamAdmin()) {
//            boolean flag = Objects.isNull(command.getTeamId());
//            List<Team> teams = teamService.getTeamListByUserId(userId);
//            if (CollUtil.isEmpty(teams)) return PageResult.success(Collections.emptyList(), 0);
//            if (flag) command.setTeamId(teams.get(0).getId());
//        }
//        return orderQueryAdminService.orderUserApplyAllocationPageQueryByDataRole(command);
//    }
//
    @Operation(summary = "产品下拉接口-商户端", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/productsByDataRole")
    public Result<List<ProductListDTO>> productsByDataRole() {
        Long userId = SecurityUtils.X.getUser().getUserId();
        List<Long> merchantIds = userQueryService.getUserMerchantIds(userId);
        if (CollUtil.isEmpty(merchantIds)) {
            return Result.success(new ArrayList<>());
        }
        Long merchantId = merchantIds.get(0);
        //商户管理员和商户用户角色只能查询自己商户下的产品
        List<ProductListDTO> productDetailDTOS = productQueryAdminService.listProductByMerchantIdAndUserId(merchantId, userId);

        return Result.success(productDetailDTOS);
    }
//
//    @Operation(summary = "分页查询用户申请分配订单列表-商户端", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping("/export/merchant")
//    public ResponseEntity<byte[]> orderUserApplyAllocationPageQueryByDataRoleExport(@Validated @RequestBody OrderUserApplyAllocationMerchantPageCommand command)   throws IOException{
//
//        List<OrderUserApplyAllocationMerchantPageDTO> result = orderQueryAdminService.orderUserApplyAllocationPageQueryByDataRolelist(command);
//
//        // 创建工作簿
//        Workbook workbook = new XSSFWorkbook();
//        // 创建工作表
//        Sheet sheet = workbook.createSheet("Sheet1");
//
//        // 创建标题行
//        Row headerRow = sheet.createRow(0);
//        // 设置表头
//        headerRow.createCell(0).setCellValue("订单号");
//        headerRow.createCell(1).setCellValue("用户名称");
//        headerRow.createCell(2).setCellValue("手机号");
//        headerRow.createCell(3).setCellValue("申请产品");
//        headerRow.createCell(4).setCellValue("贷款金额");
//        headerRow.createCell(5).setCellValue("贷款期限");
//        headerRow.createCell(6).setCellValue("申请时间");
//        headerRow.createCell(7).setCellValue("分配子账号");
//        headerRow.createCell(8).setCellValue("状态");
//        headerRow.createCell(9).setCellValue("分配时间");
//        headerRow.createCell(10).setCellValue("备注");
//        // 填充数据 从第二行开始
//        int rowNum = 1;
//        for (OrderUserApplyAllocationMerchantPageDTO dto : result) {
//            // 将Date对象格式化为指定格式的字符串
//            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String allocationTime = outputFormat.format(dto.getAllocationTime());
//            String submit = outputFormat.format(dto.getSubmitTime());
//            Row row = sheet.createRow(rowNum);
//            row.createCell(0).setCellValue(dto.getApplyOrderNo());
//            row.createCell(1).setCellValue(dto.getUserName());
//            row.createCell(2).setCellValue(dto.getUserPhone());
//            row.createCell(3).setCellValue(dto.getProductName());
//            row.createCell(4).setCellValue(dto.getLoanAmount().toString());
//            if(dto.getLoanPeriod()==1){
//                row.createCell(5).setCellValue("3个月");
//            } else if (dto.getLoanPeriod()==2) {
//                row.createCell(5).setCellValue("6个月");
//            }
//            else if (dto.getLoanPeriod()==3) {
//                row.createCell(5).setCellValue("9个月");
//            }
//            else if (dto.getLoanPeriod()==4) {
//                row.createCell(5).setCellValue("12个月");
//            }
//            else if (dto.getLoanPeriod()==5) {
//                row.createCell(5).setCellValue("24个月");
//            }
//            row.createCell(6).setCellValue(submit);
//            row.createCell(7).setCellValue(dto.getCurrentAccountName());
//            if(dto.getOrderStatus()!=null){
//                if(dto.getOrderStatus()==1){
//                    row.createCell(8).setCellValue("待处理");
//                }else if (dto.getOrderStatus()==2) {
//                    row.createCell(8).setCellValue("待跟进");
//                }else if (dto.getOrderStatus()==3) {
//                    row.createCell(8).setCellValue("有效客户");
//                }
//                else if (dto.getOrderStatus()==4) {
//                    row.createCell(8).setCellValue("无效客户");
//                }
//
//            }
//            row.createCell(9).setCellValue(allocationTime);
//            row.createCell(10).setCellValue(dto.getRemark());
//            rowNum ++ ;
//        }
//
//        // 将工作簿写入 ByteArrayOutputStream
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        workbook.write(byteArrayOutputStream);
//
//        // 设置响应头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentDispositionFormData("attachment",URLEncoder.encode("分配单列表-商户端",StandardCharsets.UTF_8.toString()) + ".xlsx");
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//
//        // 返回 Excel 文件的字节数组
//        return new ResponseEntity<>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK);
//
//    }
//
//    @Operation(summary = "分页查询用户申请分配订单列-平台端", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping("/orderUserApplyAllocationPageQuery")
//    public PageResult<OrderUserApplyAllocationPageDTO> orderUserApplyAllocationPageQuery(@Validated @RequestBody OrderUserApplyAllocationPageCommand command) {
//        return orderQueryAdminService.orderUserApplyAllocationPageQuery(command);
//    }
//
//
//    @Operation(summary = "分页查询二次uv统计表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping("/twoUvOrderStatistics")
//    public PageResult<ChannelPromotionTwoUvStatisticsDto> twoUvOrderStatistics(@Validated @RequestBody OrderUserApplyAllocationPageCommand command) {
//        return orderQueryAdminService.twoUvOrderStatistics(command);
//    }
//
//
//
//    @Operation(summary = "导出分配单列表-平台端", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping("/export")
//    public ResponseEntity<byte[]> export(@RequestBody OrderUserApplyAllocationPageCommand command) throws IOException {
//        List<OrderUserApplyAllocationPageDTO> result = orderQueryAdminService.orderUserApplyAllocationPageQueryList(command);
//        // 创建工作簿
//        Workbook workbook = new XSSFWorkbook();
//        // 创建工作表
//        Sheet sheet = workbook.createSheet("Sheet1");
//
//        // 创建标题行
//        Row headerRow = sheet.createRow(0);
//        // 设置表头
//        headerRow.createCell(0).setCellValue("订单号");
//        headerRow.createCell(1).setCellValue("用户名称");
//        headerRow.createCell(2).setCellValue("手机号");
//        headerRow.createCell(3).setCellValue("分配商户");
//        headerRow.createCell(4).setCellValue("分配产品");
//        headerRow.createCell(5).setCellValue("年龄");
//        headerRow.createCell(6).setCellValue("城市");
//        headerRow.createCell(7).setCellValue("芝麻分");
//        headerRow.createCell(8).setCellValue("渠道来源");
//        headerRow.createCell(9).setCellValue("链接名称");
//        headerRow.createCell(10).setCellValue("申请时间");
//        headerRow.createCell(11).setCellValue("分配时间");
//        headerRow.createCell(12).setCellValue("企业微信");
//
//        // 填充数据 从第二行开始
//        int rowNum = 1;
//        for (OrderUserApplyAllocationPageDTO dto : result) {
//            // 将Date对象格式化为指定格式的字符串
//            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String allocationTime = outputFormat.format(dto.getAllocationTime());
//            String submit = outputFormat.format(dto.getSubmitTime());
//            Row row = sheet.createRow(rowNum);
//            row.createCell(0).setCellValue(dto.getApplyOrderNo());
//            row.createCell(1).setCellValue(dto.getUserName());
//            row.createCell(2).setCellValue(dto.getUserPhone());
//            row.createCell(3).setCellValue(dto.getMerchantName());
//            row.createCell(4).setCellValue(dto.getProductName());
//            row.createCell(5).setCellValue(dto.getAge());
//            row.createCell(6).setCellValue(dto.getApplyCity());
//            row.createCell(7).setCellValue(dto.getSesameSeedQuotaStr());
//            row.createCell(8).setCellValue(dto.getChannelName());
//            row.createCell(9).setCellValue(dto.getChannelPromotionName());
//            row.createCell(10).setCellValue(submit);
//            row.createCell(11).setCellValue(allocationTime);
//            row.createCell(12).setCellValue(dto.getUserWechat());
//            rowNum ++ ;
//        }
//        // 将工作簿写入 ByteArrayOutputStream
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        workbook.write(byteArrayOutputStream);
//
//        // 设置响应头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentDispositionFormData("attachment",URLEncoder.encode("分配单列表-平台端",StandardCharsets.UTF_8.toString()) + ".xlsx");
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//
//        // 返回 Excel 文件的字节数组
//        return new ResponseEntity<>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK);
//
//        }
//
//
}